package com.uxsino.commons.logicSelector;

import java.util.function.Function;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.uxsino.commons.logicSelector.propFunction.IPropValueFunction;

public class PropSelector<ObjectType> extends AbstractSelector<ObjectType> {

    @JsonProperty("name")
    @JSONField(name = "name")
    private String propExpr;

    @JsonProperty("value")
    @JSONField(name = "value")
    private String propValue;

    @JsonProperty("op")
    @JSONField(name = "op")
    private String opName;

    IPropValueFunction valueFunc;

    @JsonCreator
    public PropSelector() {
    }

    public PropSelector(String propExpr, String opName, String value) {
        this.propValue = value;
        this.propExpr = propExpr;
        this.opName = opName;

    }

    @Override
    public String getSelectorTypeName() {
        return "prop";

    }

    @Override
    public boolean _accept(SelectorContext<ObjectType> context) {

        Object v = context.getValue(propExpr);

        PropOperator func = context.getOperator(opName);
        if (func != null) {
            return func.accept(context, v, propValue);
        }
        return false;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public String getOperatorName() {
        return opName;
    }

    @Override
    public boolean solveReference(Function<String, ISelector<ObjectType>> finder) {
        return true;
    }

    @Override
    public String toString() {
        return "<prop name=\"" + propExpr + "\" op=\"" + opName + "\" value=\"" + propValue + "\">";
    }

    @Override
    public String toXml() {
        return "<prop name=\"" + propExpr + "\" op=\"" + opName + "\" value=\"" + propValue + "\"/>";
    }
}
